#include "serverlink.h"

#include "registerserver.h"

namespace servermanager {

ServerLink::ServerLink(net::ISocket* socket) {
	this->socket = socket;

	dispatcher = env::GetRequestDispatcher();

	AddRequestClient(new RegisterServer(*this));
}

ServerLink::~ServerLink() {
	DestroyRequestClient();

	if(dispatcher != NULL) {
		delete dispatcher;
		dispatcher = NULL;
	}
}

void ServerLink::DestroyRequestClient() {
	REQUEST_CLIENT_LIST::iterator it = request_client_list.begin();

	for(; it != request_client_list.end(); it++) {
		delete *it;
	}
	request_client_list.clear();
}

net::ISocket* ServerLink::GetSocket() {
	return socket;
}

void ServerLink::AddRequestClient(tool::IRequestClient* client) {
	request_client_list.push_back(client);

	dispatcher->AddRequestClient(client);
}

void ServerLink::RemoveRequestClient(tool::IRequestClient* client) {
	REQUEST_CLIENT_LIST::iterator it = request_client_list.begin();

	for(; it != request_client_list.end(); it++) {
		if(*it == client) {
			request_client_list.erase(it);
			return ;
		}
	}
}

void ServerLink::OnRead(net::ISocket* socket) {
	pack::Request request(socket->GetInBuffer());

	while(request.GetPack()) {
		dispatcher->OnRequest(request);
	}
}

void ServerLink::OnWrite(net::ISocket* socket) {

}

void ServerLink::OnClose(net::ISocket* socket) {

}

void ServerLink::OnConnected(net::ISocket* socket) {

}

void ServerLink::OnError(net::ISocket* socket, uint32_t error) {

}

}
